﻿using Coldairarrow.Entity.Base_AutoReplys;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Base_AutoReplys
{
    public class Base_ARGroupBusiness : BaseBusiness<Base_ARGroup>, IBase_ARGroupBusiness, ITransientDependency
    {
        public Base_ARGroupBusiness(IDbAccessor repository)
            : base(repository)
        {
        }

        #region 外部接口

        public async Task<PageResult<Base_ARGroup>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<Base_ARGroup>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<Base_ARGroup, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<Base_ARGroup> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(Base_ARGroup data)
        {
            var aCount = GetIQueryable().Where(x => x.GroupName.Equals(data.GroupName)).Count();
            if (aCount > 0)
            {
                throw new BusException("分类名称已存在，请修改后重试！");
            }

            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(Base_ARGroup data)
        {
            var aCount = GetIQueryable().Where(x => x.GroupName.Equals(data.GroupName) && !x.Id.Equals(data.Id)).Count();
            if (aCount > 0)
            {
                throw new BusException("分类名称与其他分类名称重复，请修改后重试！");
            } 
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        /// <summary>
        /// 获取回复分组列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<Base_ARGroup>> GetListDataAsnyc()
        {
            List<Base_ARGroup> list = new List<Base_ARGroup>();

            var dList = await GetIQueryable().OrderBy(x => x.Sort).ToListAsync();

            return dList;
        }
        #endregion

        #region 私有成员

        #endregion
    }
}